'''
获取地图

原理 
1.调用阿里云提供的GeoAtlas获取Geojson
2.用mapshaper将Geojson转化为svg
3.用自定义参数美化svg
4.用caitosvg将svg转换为png
5.覆盖掉资源文件夹里面的旧文件
'''
import requests
import json
import os
import xml.etree.ElementTree as et

from .config import *

def get_geojson(zip_code):
    url = f"https://geo.datav.aliyun.com/areas_v3/bound/{zip_code}.json"

    data = requests.get(url)

    data = data.content
    data = data.decode("UTF-8")

    data = json.loads(data)

    with open("temp/data.json", 'w') as f:
        json.dump(data, f)

def geojson2svg():
    os.system(f"{os.getcwd()}\\lib\\mapshaper.cmd -i ./temp/data.json -o format=svg ./temp/data.svg")

def processsvg():
    tree = et.parse("./temp/data.svg")
    root = tree.getroot()

    path = root[0][0]

    for k, w in dict(config["svgstyle"]).items():
        path.set(k, w)
            
    tree.write('temp/data.svg', encoding='UTF-8', xml_declaration=True)

def svg2png():
    os.system(f"cairosvg ./temp/data.svg -o ./temp/data.png")

def process(zipcode):
    get_geojson(zipcode)
    geojson2svg()
    processsvg()
    svg2png()

    f = open("temp/data.png", 'rb')
    g = open("./@Resources/data.png", 'wb')

    g.write(f.read())

    f.close()
    g.close()

def clear():
    g = open("./@Resources/data.png", 'wb')
    g.close()
    